package com.hjrpc.babyyamall.authserver.web;

import com.hjrpc.babyyamall.authserver.feign.MemberFeignService;
import com.hjrpc.babyyamall.authserver.vo.UserLoginVo;
import com.hjrpc.common.dto.LoginUserTo;
import com.hjrpc.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@Slf4j
public class LoginController {

    @Autowired
    MemberFeignService memberFeignService;

    @PostMapping("/login")
    public String login(@Validated UserLoginVo userLoginVo, BindingResult result,
                        RedirectAttributes attributes, HttpSession session) {
        if (result.hasErrors()) {
            attributes.addFlashAttribute("errors", result.getFieldErrors().stream()
                    .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage, (v1, v2) -> v1 + "," + v2)));
            return "redirect:http://auth.babyyamall.com/login.html";
        }
        // 远程调用会员服务
        R r = memberFeignService.login(userLoginVo);
        if (r.isSuccess()) {
            LoginUserTo loginUser = r.getData(LoginUserTo.class);
            log.info("返回的数据：{}", loginUser);
            session.setAttribute("loginUser", loginUser);
            return "redirect:http://babyyamall.com";
        }
        String msg = (String) r.get("msg");
        Map<String, String> errors = new HashMap<>();
        errors.put("msg", msg);
        attributes.addFlashAttribute("errors", errors);
        return "redirect:http://auth.babyyamall.com/login.html";
    }

    @GetMapping("/login.html")
    public String loginHtml(HttpSession session) {
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser != null) {
            return "redirect:http://babyyamall.com";
        }
        return "login";
    }

}
